import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;


/** 
 * This is the panel used to select a ticket type for a particular showing
 * and enter the purchase in the database.
 * @author Travis, Chris
 */
public class PurchaseTicketDialog extends JDialog {
	private static final long serialVersionUID = -8141705879358050085L;

	private final JPanel contentPanel = new JPanel();
	
	private final ShowingRow show;
	private final DatabaseInfo db_info;
	
	private String[] ticketTypes;
	
	private JComboBox<String> ticketTypeBox;
	
	/**
	 * Create the dialog.
	 */
	public PurchaseTicketDialog(final ShowingRow the_show, 
			final DatabaseInfo the_db_info) 
	{
		show = the_show;
		db_info = the_db_info;
		getTicketTypes();
		
		setBounds(100, 100, 444, 230);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		{
			JLabel lblAddMovie = new JLabel("Purchase Ticket");
			lblAddMovie.setFont(new Font("Tahoma", Font.BOLD, 16));
			lblAddMovie.setBounds(158, 11, 149, 14);
			contentPanel.add(lblAddMovie);
		}
		
		// movie title labels
		JLabel lblTitle = new JLabel("Movie:");
		lblTitle.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblTitle.setBounds(53, 47, 43, 14);
		contentPanel.add(lblTitle);
		
		JLabel title_assign = new JLabel(show.getTitle());
		title_assign.setFont(new Font("Tahoma", Font.PLAIN, 13));
		title_assign.setBounds(100,47,300,14);
		contentPanel.add(title_assign);
		
		// cinema name labels
		JLabel lblCinema = new JLabel("Cinema:");
		lblCinema.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblCinema.setBounds(53, 72, 58, 14);
		contentPanel.add(lblCinema);
		
		JLabel cinema_assign = new JLabel(show.getCName());
		cinema_assign.setFont(new Font("Tahoma", Font.PLAIN, 13));
		cinema_assign.setBounds(110,70,300,18);
		contentPanel.add(cinema_assign);
		
		// show time labels
		JLabel lblTime = new JLabel("Time:");
		lblTime.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblTime.setBounds(53, 97, 43, 14);
		contentPanel.add(lblTime);
		
		JLabel time_assign = new JLabel(show.getTimeString());
		time_assign.setFont(new Font("Tahoma", Font.PLAIN, 13));
		time_assign.setBounds(100,97,100,14);
		contentPanel.add(time_assign);
		
		//ticket type label and combobox
		JLabel lblTicketType = new JLabel("Ticket Type:");
		lblTicketType.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblTicketType.setBounds(53, 122, 71, 14);
		contentPanel.add(lblTicketType);
		
		ticketTypeBox = new JComboBox<String>(ticketTypes);
		ticketTypeBox.setBounds(134, 120, 128, 20);
		contentPanel.add(ticketTypeBox);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("Confirm");
				okButton.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						boolean result = purchaseTicket();
						if(!result) {
							JOptionPane.showMessageDialog(null,
								    "An error has occured, ticket not purchased.",
								    "Purchase Error",
								    JOptionPane.ERROR_MESSAGE);
						}
						else {
							JOptionPane.showMessageDialog(null, "Ticket purchased!",
									"Purchase Success",
									JOptionPane.PLAIN_MESSAGE);
						}
						dispose();
					}
				});
				okButton.setActionCommand("Confirm");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
		
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setVisible(true);
	}
	
	/**
	 * This is where the purchase info actually gets inserted into
	 * the database.
	 * @return <code>true</code> if the purchase info was successfully
	 * inserted into the database, <code>false</code> if there was
	 * an error or exception.
	 */
	private boolean purchaseTicket() {
		Db db = Db.getDb();
		
		StringBuilder sb = new StringBuilder();
		sb.append("INSERT INTO purchases(cName,title,accountID,ticketType) VALUES ('");
		sb.append(show.getCName());
		sb.append("','");
		sb.append(show.getTitle());
		sb.append("','");
		sb.append(db_info.getAccountID());
		sb.append("','");
		sb.append(ticketTypes[ticketTypeBox.getSelectedIndex()]);
		sb.append("');");
		
		try {
			db.executeNonQuery(db_info.server, db_info.database, 
					sb.toString(), db_info.user_name, db_info.password);
		} catch (Exception e1) {
			System.out.println(e1.getMessage());
			e1.printStackTrace();
			return false;
		}
		
		return true;
	}

	/**
	 * Gets the ticket types available for purchase at the theater the
	 * movie is showing at.
	 * @return <code>true</code> if the query successfully obtained the
	 * ticket types.
	 */
	private boolean getTicketTypes() {
		Db db = Db.getDb();
		String query = "SELECT * FROM tickets WHERE cName='" 
				+ show.getCName() + "';";
		
		String result = null;
		
		try {
			result = db.executeQuery(db_info.server, db_info.database, query, 
					db_info.user_name, db_info.password);
		} catch (Exception e1) {
			System.out.println(e1.getMessage());
			e1.printStackTrace();
			return false;
		}
		
		if(null != result) {
			String[] splits = result.split("\r");
			ArrayList<TicketInfo> tickets = new ArrayList<TicketInfo>();
			
			for(int i = 1 ; i < splits.length - 1 ; i++) 
				tickets.add(new TicketInfo(splits[i].trim()));
			
			ticketTypes = new String[tickets.size()];
			for(int i = 0 ; i < ticketTypes.length ; i++)
				ticketTypes[i] = tickets.get(i).ticketType;
		}
		
		return true;
	}
	
	/**
	 * A class that holds the information of tuples in the tickets relation.
	 * The class is pretty much unused but I didn't want to delete it...
	 * @author Travis
	 */
	private class TicketInfo {
		private String ticketType;
		private String ticketPrice;
		private String cName;
		
		//formatted as a row from the tickets relation
		public TicketInfo(String row_data) {
			cName = row_data.substring(0, row_data.indexOf('\t'));
			row_data = row_data.substring(row_data.indexOf('\t')).trim();
			ticketType = row_data.substring(0, row_data.indexOf('\t'));
			row_data = row_data.substring(row_data.indexOf('\t')).trim();
			ticketPrice = row_data;
		}
		
		@SuppressWarnings("unused")
		public String getTicketType() { return ticketType; }
		@SuppressWarnings("unused")
		public String getTicketPrice() {return ticketPrice; }
		@SuppressWarnings("unused")
		public String getCName() { return cName; }
		
		@Override
		public String toString() {
			return cName + "\t" + ticketType + "\t" + ticketPrice;
		}
	}
}
